<template>
  <div style="width: 100%; margin-top: 50px;">
    <a-row>
      <a-col :span="5" :offset="1">
        <a-card title="服务选择">
          <a-tree
            :default-selected-keys="['stock']"
            @select="onSelect"
            :treeData="treeData" />
        </a-card>
      </a-col>
      <a-col :span="16" :offset="1">
        <a-card title="服务API列表">
          <div :class="advanced ? 'search' : null">
            <a-form layout="inline">
              <div :class="advanced ? null: 'fold'" style="text-align: right;">
                <a-form-item style="margin-right: 20px; margin-top: 3px;">
                </a-form-item>
              </div>
            </a-form>
            <div class="operator" style="float: left;width: 100%;margin: -20px 0 10px;">
              <a-button v-hasPermission="'api:add'" type="primary" ghost @click="add" style="margin-left: 20px;">新增</a-button>
              <a-button v-hasPermission="'api:delete'" @click="batchDelete">删除</a-button>
            </div>
            <a-table ref="TableInfo"
                     :columns="columns"
                     :dataSource="dataSource"
                     :pagination="pagination"
                     :loading="loading"
                     @change="handleTableChange"
                     :scroll="{ x: 900 }"
                     style="margin-left: 10px;margin-top: 15px;"
                     :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
                     :rowKey="record => record.name">
              <template slot="operation" slot-scope="text, record">
                <a-icon v-hasPermission="'api:update'" type="setting" theme="twoTone" twoToneColor="#4a9ff5" @click="edit(record)" title="修改服务API"></a-icon>
              </template>
            </a-table>
          </div>
          <!-- 新增类别 -->
          <api-add
            @close="handleApiAddClose"
            @success="handleApiAddSuccess"
            :apiAddVisiable="apiAddVisiable">
          </api-add>
          <!-- 修改类别 -->
          <api-edit
            ref="apiEdit"
            @close="handleApiEditClose"
            @success="handleApiEditSuccess"
            :apiEditVisiable="apiEditVisiable">
          </api-edit>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import ApiAdd from './ApiAdd'
import ApiEdit from './ApiEdit'
import defaultPagination from '../../../utils/common'
export default {
  name: 'Api',
  components: {
    ApiAdd,
    ApiEdit
  },
  data () {
    return {
      treeData: [],
      advanced: false,
      apiAddVisiable: false,
      apiEditVisiable: false,
      dataSource: [],
      selectedRowKeys: [],
      filteredInfo: null,
      paginationInfo: null,
      pagination: defaultPagination,
      queryParams: {},
      loading: false,
      serviceSN: 'stock'
    }
  },
  computed: {
    columns () {
      // eslint-disable-next-line no-unused-vars
      let { filteredInfo } = this
      filteredInfo = filteredInfo || {}
      return [{
        title: 'API名称',
        dataIndex: 'name'
      }, {
        title: '请求方式',
        dataIndex: 'method'
      }, {
        title: '地址前缀(域名)',
        dataIndex: 'urlPrefix'
      }, {
        title: '接口地址',
        dataIndex: 'url'
      }, {
        title: '操作',
        dataIndex: 'operation',
        scopedSlots: {
          customRender: 'operation'
        }
      }]
    }
  },
  mounted () {
    this.fetch({
      ...this.queryParams
    })
    this.initTree()
  },
  methods: {
    initTree () {
      let aa = {}
      aa.ignoreName = ''
      this.$get('/serviceInfo/api/tree', aa).then((r) => {
        let result = r.data
        this.treeData = result
      })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    search () {
      let {filteredInfo} = this
      this.restPagination()
      this.fetch({
        ...this.queryParams,
        ...filteredInfo
      })
    },
    onSelect (selectedKeys) {
      this.selectedRowKeys = []
      this.serviceSN = selectedKeys
      this.fetch({
        ...this.queryParams
      })
    },
    handleApiAddSuccess () {
      this.apiAddVisiable = false
      this.$message.success('新增服务API成功')
      this.search()
    },
    handleApiAddClose () {
      this.apiAddVisiable = false
    },
    add () {
      this.apiAddVisiable = true
    },
    handleApiEditSuccess () {
      this.apiEditVisiable = false
      this.$message.success('修改服务API成功')
      this.search()
    },
    handleApiEditClose () {
      this.apiEditVisiable = false
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      let serviceSN = this.serviceSN
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk () {
          let apiNames = that.selectedRowKeys.join(',')
          that.$delete('/serviceInfo/api/delete/' + apiNames + '/' + serviceSN).then(() => {
            that.$message.success('删除成功')
            that.selectedRowKeys = []
            that.search()
          }).catch(() => {
            this.loading = false
            that.$message.error('删除失败')
          })
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
    edit (record) {
      record.serviceSN = this.serviceSN
      this.$refs.apiEdit.setFormValues(record)
      this.apiEditVisiable = true
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      this.restPagination()
      // 重置列过滤器规则
      this.filteredInfo = null
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.queryParams = {}
      this.fetch()
    },
    restPagination () {
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
    },
    handleTableChange (pagination, filters, sorter) {
      this.paginationInfo = pagination
      this.filteredInfo = filters
      this.fetch({
        ...this.queryParams,
        ...filters
      })
    },
    fetch (params = {}) {
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
        params.areaId = this.queryAreaId
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      params.serviceSN = this.serviceSN
      this.$get('/serviceInfo/api', {
        ...params
      }).then((r) => {
        let data = r.data
        const pagination = { ...this.pagination
        }
        pagination.total = data.total
        this.loading = false
        this.dataSource = data.rows
        this.pagination = pagination
      })
    }
  }
}
</script>
